<?php
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', '1');

/**
 * @author SilverBiology, LLC
 */

session_start();
include_once('../../config.php');

function arguments($args){
	array_shift( $args );
	$args = join( $args, ' ');
	preg_match_all('/ (--\w+ (?:[= ] [^-]+ [^\s-] )? ) | (-\w+) | (\w+) /x', $args, $match );
	$args = array_shift( $match );

	$ret = array(
			'input'    => array(),
			'commands' => array(),
			'flags'    => array()
	);
	
	foreach ( $args as $arg ) {
		// Is it a command? (prefixed with --)
		if ( substr( $arg, 0, 2 ) === '--' ) {

			$value = preg_split( '/[= ]/', $arg, 2 );
			$com   = substr( array_shift($value), 2 );
			$value = join($value);

			$ret['commands'][$com] = !empty($value) ? $value : true;
			continue;
		}
	
		// Is it a flag? (prefixed with -)
		if ( substr( $arg, 0, 1 ) === '-' ) {
			$ret['flags'][] = substr( $arg, 1 );
			continue;
		}

		$ret['input'][] = $arg;
		continue;	
	}	
	return $ret;
}

function dir_tree($dir) {
 $path = '';
 $stack[] = $dir;
 while ($stack) {
	 $thisdir = array_pop($stack);
	 if ($dircont = scandir($thisdir)) {
		 $i=0;
		 while (isset($dircont[$i])) {
			 if ($dircont[$i] !== '.' && $dircont[$i] !== '..') {
				 $current_file = "{$thisdir}/{$dircont[$i]}";
				 if (is_file($current_file)) {
					 $path[] = "{$thisdir}/{$dircont[$i]}";
				 } elseif (is_dir($current_file)) {
						$path[] = "{$thisdir}/{$dircont[$i]}";
						$stack[] = $current_file;
				 }
			 }
			 $i++;
		 }
	 }
 }
 return $path;
}

$expected = array(
		'cmd'
	,	'id'
	,	'state'
	,	'locality'
	,	'description'
	,	'stage'
	,	'lastModified'
	,	'imageId'
	,	'county'
	,	'limit'
	,	'start'
	,	'end'
	,	'dir'
	,	'sort'
	,	'filter'
	,	'query'
	,	'type'
	,	'public'
	,	'vernacularName'
	,	'significance'
	,	'html'
	,	'sex'
	,	'age'
	,	'dateObserved'
	,	'verbatimDate'
	,	'characteristics'
	,	'numberSeen'
	,	'observers'
	,	'contactInfo'
	,	'audioRec'
	,	'audioRecUri'
	,	'heardOnly'
	,	'photo'
	,	'photoUri'
	,	'sightRec'
	,	'specimen'
	,	'species'
	,	'video'
	,	'videoUri'
	,	'name'
	,	'path'
	, 'auth'
	,	'email'
	,	'permission'
	,	'user_id'
	,	'password'
	,	'markedPrinted'
	,	'printed'
	,	'recaptcha_challenge_field'
	,	'recaptcha_response_field'
	,	'public'
	,	'output'
	,	'occurrence_id'
	,	'col'
);

// Initialize allowed variables
foreach ($expected as $formvar)
	$$formvar = (isset(${"_$_SERVER[REQUEST_METHOD]"}[$formvar])) ? ${"_$_SERVER[REQUEST_METHOD]"}[$formvar]:NULL;

#print "<pre>";	
#print $config['basePath'];
#print_r( glob($config['basePath'] . "resources/api/*"));
require_once( $config['basePath'] . 'resources/api/class.lsu.php');
$lsu = new Lsu;
$valid = true;
$code = 0;

include_once('./access_user/access_user_class.php');
$accessUser = new Access_user( DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME );
#print_r( arguments( $argv ) );
#exit();

switch($cmd){

	case 'newOccurrence':
		include_once('class.speciesoccurrence.php');
		include_once('recaptchalib.php');
		$spOcc = new SpeciesOccurrence();
		$resp = recaptcha_check_answer(PRIVATEKEY, $_SERVER["REMOTE_ADDR"],  $recaptcha_challenge_field, $recaptcha_response_field);
		if ($resp->is_valid) {
#		if (true) {
			$auth = uniqid();
			
			$tmp = explode("/", $dateObserved);
			$dateObserved = $tmp[2] . "-" . $tmp[0] . "-" . $tmp[1];
			if ($dateObserved == "--") $dateObserved = "";
			
			$spOcc->set("vernacularName", $vernacularName); 
			$spOcc->set("numberSeen", $numberSeen); 
			$spOcc->set("sex", $sex); 
			$spOcc->set("age", $age); 
			$spOcc->set("characteristics", $characteristics); 
			$spOcc->set("state", $state); 
			$spOcc->set("verbatimDate", $verbatimDate); 
			$spOcc->set("dateObserved", $dateObserved); 
			$spOcc->set("locality", $locality); 
			$spOcc->set("description", $description); 
			$spOcc->set("observers", $observers); 
			$spOcc->set("contactInfo", $contactInfo); 
			$spOcc->set("imageId", $imageId); 
			$spOcc->set("county", $county); 
			$spOcc->set("significance", $significance); 
			$spOcc->set("audioRec", $audioRec); 
			$spOcc->set("audioRecUri", $audioRecUri); 
			$spOcc->set("heardOnly", $heardOnly); 
			$spOcc->set("photo", $photo); 
			$spOcc->set("photoUri", $photoUri); 
			$spOcc->set("sightRec", $sightRec); 
			$spOcc->set("specimen", $species); 
			$spOcc->set("video", $video); 
			$spOcc->set("videoUri", $videoUri); 
			$spOcc->set("auth", $auth); 
			$spOcc->set("filename", $filename); 
			$spOcc->set("path", $path); 
			$spOcc->set("markedPrinted", $markedPrinted); 
			$spOcc->set("check_out", $check_out); 
			$spOcc->set("check_in", $check_in); 
			$spOcc->set("originalPath", $originalPath); 

			$spOcc->set("stage", 'Pending');

			$result = $spOcc->save();
			$spOcc->sendEmail($spOcc->get("id"), $auth);
			
#			$result = $spOcc->saveData($vernacularName, $numberSeen, $sex, $age, $characteristics, $state, $verbatimDate, $locality, $description, $stage, $observers, $contactInfo, $imageId, $county, $significance, $audiorec, $audioRecUri, $heardonly, $photo, $photoUri, $sightrec, $specimen, $video, $videoUri, $name, $path);

			if($result){
				print json_encode(array("success" => true, "results" => "Record added successfully.", "id" => $spOcc->get("id") ));
			} else {
				print json_encode(array("success" => false, "error" => mysql_error()));
			}
		} else {
			print ( json_encode( array('success' => false, 'error' => "The reCAPTCHA was not entered correctly.") ) ) ;
		}
		break;

	case 'listData':
		include_once('class.speciesoccurrence.php');
		$spOcc = new SpeciesOccurrence();
		$filterReq = @json_decode(stripslashes($filter),true);
		if ($limit == '') $limit = 50;
		if ($occurrence_id != '') {
			$t = array('value' => $occurrence_id, 'field' => 'id', 'type' => 'integer');
			$filterReq[] = $t;
		}
		
		$posts = $spOcc->listData($dir, $sort, $filterReq, $public, $limit, $start);

		header('Content-type: application/json');
		if ($posts) {
			print json_encode(array( 'success' => true, 'totalCount' => $spOcc -> getCount(), 'data' => $posts));
		} else {
			print json_encode(array('success' => true, 'data' => array()));
		}
    break;

	case 'list':
		include_once('class.speciesoccurrence.php');
		$spOcc = new SpeciesOccurrence();		
		$posts = $spOcc->showList($query, $type);
		header('Content-type: application/json');
		if($posts) {
			print json_encode( array( 'success' => true, 'data' => $posts));
		} else {
			print json_encode(array("success" => false, "error" => "Record not found."));
		}
		break;

	case 'updateData':
		header('Content-type: application/json');
		include_once('class.speciesoccurrence.php');
		$spOcc = new SpeciesOccurrence();
		$result = $spOcc->load_by_id($id);

		$tmp = explode("/", $dateObserved);
		$dateObserved = $tmp[2] . "-" . $tmp[0] . "-" . $tmp[1];
		if ($dateObserved == "--") $dateObserved = "";

		if ($result) {
			if ($spOcc->get("auth") == $auth) {
				$spOcc->set("vernacularName", $vernacularName); 
				$spOcc->set("numberSeen", $numberSeen); 
				$spOcc->set("sex", $sex); 
				$spOcc->set("age", $age); 
				$spOcc->set("characteristics", $characteristics); 
				$spOcc->set("state", $state); 
				$spOcc->set("verbatimDate", $verbatimDate); 
				$spOcc->set("dateObserved", $dateObserved); 
				$spOcc->set("locality", $locality); 
				$spOcc->set("description", $description); 
				$spOcc->set("observers", $observers); 
				$spOcc->set("contactInfo", $contactInfo); 
				$spOcc->set("imageId", $imageId); 
				$spOcc->set("county", $county); 
				$spOcc->set("significance", $significance); 
				$spOcc->set("audioRec", $audioRec); 
				$spOcc->set("audioRecUri", $audioRecUri); 
				$spOcc->set("heardOnly", $heardOnly); 
				$spOcc->set("photo", $photo); 
				$spOcc->set("photoUri", $photoUri); 
				$spOcc->set("sightRec", $sightRec); 
				$spOcc->set("specimen", $species); 
				$spOcc->set("video", $video); 
				$spOcc->set("videoUri", $videoUri); 
				if (isset($filename)) $spOcc->set("filename", $filename); 
				if (isset($path)) $spOcc->set("path", $path); 
				if (isset($markedPrinted)) $spOcc->set("markedPrinted", $markedPrinted); 
	//			if (isset($check_out)) $spOcc->set("check_out", $check_out); 
				$spOcc->set("check_in", @date('Y-m-d H:i:s'));
				$spOcc->set("modifiedBy", $_SESSION['user']);
				$spOcc->set("stage", "Pending"); 
				
				$result = $spOcc->save(1);

				if($result){
					print json_encode(array("success" => true, "results" => "Record updated successfully." ));
				} else {
					print json_encode(array("success" => false, "error" => mysql_error()));
				}

			} else {
				print json_encode(array("success" => false, "error" => "Authentication Failed"));
			}
		}
		break;

	case 'updateStatus':
		include_once('class.speciesoccurrence.php');
		$spOcc = new SpeciesOccurrence();		
		$result = $spOcc->updateStatus($id, $stage, $auth, $public);
		
		if ($output == "html") {
			print "Observation $id: Status set to $stage.";
		} else {
			header('Content-type: application/json');
			if($result){
				print json_encode(array("success" => true, "results" => "Stage updated successfully." ));
			} else {
				print json_encode(array("success" => false, "error" => 'Invalid authorization.'));
			}
		}
		break;

	case 'linkImage':
		header('Content-type: application/json');
		include_once('class.speciesoccurrence.php');
		$spOcc = new SpeciesOccurrence();
		$occurrenceId = trim($_REQUEST['occurrenceId']);
		$result = $spOcc->linkImage($occurrenceId);
		if($result){
			print json_encode(array("success" => true, 'data' => $result ));
		} else {
			print json_encode(array("success" => false, "error" => 'Image Not Available'));
		}
		break;
 	
	case 'sound':
		$vernacularName = urlencode($vernacularName);
		$values = file_get_contents("http://www.xeno-canto.org/csv.php?species=" . $vernacularName . "&representative=1");
		$list = explode("\n", $values);
		for($i = 0; $i<count($list)-1; $i++) {
			$arr = explode(";", $list[$i]);
			$post[] = array('number' => $arr[0], 'genus' => $arr[1], 'species' => $arr[2], 'english' => $arr[3], 'subspecies'=> $arr[4], 'recordist'=> $arr[5], 'country'=> $arr[6],'location'=> $arr[7], 'latitude'=> $arr[8], 'longitude' => $arr[9], 'songtype' => $arr[10]);
		}

		header('Content-type: application/json');
		print json_encode(array("success" => true, "data" => $post));
		break;

	case 'getCsv':
		include_once('class.speciesoccurrence.php');
		$spOcc = new SpeciesOccurrence();
		$fileId = uniqid();
		$file = sys_get_temp_dir() . '/'. $fileId . '.csv';
		$download = 'csv_' . $fileId . '.csv';
		$filterReq = @json_decode(stripslashes($filter),true);
		$spOcc ->getCsvFile($file, $filterReq, $public);
		header('Content-type: application/csv');
		header('Content-Disposition: attachment; filename='. $download);
		readfile($file);
		unlink($file);
    break;

	case 'buildDWCA':
		include_once('class.speciesoccurrence.php');
		$spOcc = new SpeciesOccurrence();
		$file = uniqid();
		$filterReq = @json_decode(stripslashes($filter),true);
		$result = $spOcc ->buildDWCA($file, $filterReq, $public);

		$dwcaFile = './tmp/' . $file . '.zip';
		$dwcaDownload = 'dwca_' . $file . '.zip';

		if ($result) {
			header("Content-type: application/zip");
			header("Content-Disposition: attachment; filename = " . $dwcaDownload);
	 		header("Pragma: no-cache");
	 	 	header("Expires: 0");
			readfile($dwcaFile);
	 		exit;
		} else {
			print json_encode(array("success" => false, "error" => 'Unable to Export DWCA.'));
		}
    break;

	case 'generateUnprinted':
		require_once("dompdf/dompdf_config.inc.php");
		include_once('class.speciesoccurrence.php');
		session_write_close();
		$fileName = uniqid() . ".pdf";
		$spOcc = new SpeciesOccurrence();
		$result = $spOcc->generateUnprintedCard($markedPrinted,	$printed, $stage, $start, $end, $col);
		print $result;
#		$dompdf = new DOMPDF();
#		$dompdf->load_html($result);
#		$dompdf->render();
#		$dompdf->stream($fileName);
		break;

	case 'getPdf':
		require_once("./dompdf/dompdf_config.inc.php");
		include_once('class.speciesoccurrence.php');
		$fileName = uniqid() . ".pdf";
		$spOcc = new SpeciesOccurrence();
		$result = $spOcc->getCard($id, 1);
		$dompdf = new DOMPDF();
		$dompdf->load_html($result);
		$dompdf->render();
		$dompdf->stream($fileName);
		$spOcc->updateMarkedPrinted($id);
		break;
/*
	case 'checkNewImages':
		include_once('class.speciesoccurrence.php');
		$spOcc = new SpeciesOccurrence();
		$folderPath = $config['path']['incoming'];
		$imageCount = 0;
		if(is_dir($config['path']['incoming'])) {
			$list = dir_tree($config['path']['incoming']);
#			$handle = opendir($config['path']['incoming']);
#			while (false !== ($fileName = readdir($handle))) {
#				if( $fileName == '.' || $fileName == '..') continue;
			if ($list) {
			foreach($list as $fileName) {
#				$fileName = @basename($fileName);
				$path_parts = pathinfo($fileName);
				if ($path_parts["extension"] == "jpg") {					
					$spOcc->clearRecord();
					$spOcc->set('stage','Queue');
					$spOcc->set('filename',@basename($fileName));
					$spOcc->set('originalPath', $fileName);
					$res = $spOcc->save();
					$insertId = $spOcc->getInsertId();
					$source = $config['path']['incoming'] . $fileName;
					$barcode = getCardName($insertId);
					$destination = $config['path']['images'] . getImagePath($barcode) . $barcode . '.jpg';
					mkdir_recursive( $config['path']['images'] . getImagePath($barcode) );
	
					if ($res != false) {
						@copy($source, $destination);
						#@rename($source,$destination);
						$spOcc->load_by_id($insertId);
						$spOcc->set('filename', $barcode . '.jpg');
						$spOcc->set('path', $config['path']['images'] . getImagePath($barcode));
						$spOcc->set('imageId', $barcode);
						$spOcc->save(1);

						$imageCount++;
						# populating the queue
						$lsu->queueOccurrence->set('occurrenceId', $insertId);
						$lsu->queueOccurrence->set('imageId', $barcode);
						$lsu->queueOccurrence->save();
					}
				}
			}}
		}
		header('Content-type: application/json');
		print json_encode(array( 'success' => true , 'imageCount' => $imageCount));
		break;
*/

	 case 'sendToQueue':
		header('Content-type: application/json');
		if ($_SESSION['accessType'] == "MANAGER" || $_SESSION['accessType'] == "ADMIN") {
#		if (true == false) {
			include_once('class.speciesoccurrence.php');
			$spOcc = new SpeciesOccurrence();
			$occurrenceId = trim($_REQUEST['occurrenceId']);
			if($occurrenceId != '' && $spOcc->load_by_id($occurrenceId)) {
				if ($auth == $spOcc->get('auth')) {
					$spOcc->set('check_in', '');
					$spOcc->set('check_out', '');
					$spOcc->set('stage', 'Queue');
					$spOcc->save(1);
		
					$lsu->queueOccurrence->set('occurrenceId', $spOcc->get('id'));
					$lsu->queueOccurrence->set('imageId', $spOcc->get('imageId'));
					$lsu->queueOccurrence->save();
					print json_encode(array('success' => true));
				} else {
					print json_encode(array('success' => false, 'error' => array( 'msg' => $lsu->getError(200), 'code' => 200) ) );
				}
			} else {
				print json_encode(array('success' => false, 'error' => array( 'msg' => $lsu->getError(104), 'code' => 104) ) );
			}
		} else {
			print json_encode(array('success' => false, 'error' => array( 'msg' => $lsu->getError(200), 'code' => 200) ) );
		}
	  break;

	case 'queue_get_image':
		include_once('class.speciesoccurrence.php');
		$spOcc = new SpeciesOccurrence();
		header('Content-type: application/json');
		$time_start = time();
	/*
		if (!$user_access->is_logged_in()) {
			$valid = false;
			$code = 100;
		}
	*/
		if($valid){
			$queue_record = $lsu->queueOccurrence->popQueue();
			if($queue_record === false) {
				print json_encode( array( 'success' => false, 'error' => array('msg' => $lsu->getError(108), 'code' => 108) ) );
			} else {
				$spOcc->load_by_id($queue_record->occurrenceId);
				$spOcc->set('check_out', @date('Y-m-d H:i:s'));
				$spOcc->set('modifiedBy', $_SESSION['user']);
				$spOcc->save(1);

				$queue_record = $spOcc->record;
				$queue_record["occurrenceId"] = $spOcc->get('id');				
				$processTime = time() - $time_start ;
				print json_encode( array( 'success' => true , 'processTime' => $processTime, 'data' => $queue_record ) );
			}
		} else {
			print json_encode( array( 'success' => false, 'error' => array( 'msg' => $lsu->getError($code), 'code' => $code ) ) );
		}
		break;

	case 'queue_set_image':
		include_once('class.speciesoccurrence.php');
		$spOcc = new SpeciesOccurrence();
		header('Content-type: application/json');
		$queue_data = array();
		$occurrenceId = trim($_REQUEST['occurrenceId']);
		if($valid) {
			if($spOcc->load_by_id($occurrenceId)) {
				$spOcc->set('check_in',@date('Y-m-d H:i:s'));
				$spOcc->set('stage','Pending');
				$spOcc->save();
			}
			print json_encode( array( 'success' => true ) );
		} else {
			print json_encode( array( 'success' => false, 'error' => array( 'msg' => $lsu->getError($code), 'code' => $code ) ) );
		}
		break;

	case 'queue_manager':
		include_once('class.speciesoccurrence.php');
		$spOcc = new SpeciesOccurrence();
		header('Content-type: application/json');
		# Authentication check
	/*
		if(!$user_access->is_logged_in()){
			print json_encode( array( 'success' => false, 'error' => array('message' => $lsu->getError(100), 'code' => 100 )) );
			exit;
		}
	*/
		$filter['filter'] = array(array('data' => array('type' => 'string', 'value'=> 'Queue', 'comparison' => 'eq'),'field' => 'stage'),array('data' => array('type' => 'string', 'value'=> '0000-00-00 00:00:00', 'comparison' => 'ne'),'field' => 'check_out'),array('data' => array('type' => 'string', 'value'=> '0000-00-00 00:00:00', 'comparison' => 'eq'),'field' => 'check_in'));
		$images = $spOcc->load_by_filter($filter);

		if(count($images) && is_array($images)) {
			foreach($images as $image) {
				if( ( (time() - @strtotime($image->check_out)) / 60 ) >= 1 ){
					$spOcc->load_by_id($image->id);
					$spOcc->set('check_in','');
					$spOcc->set('check_out','');
					$spOcc->save();

					$lsu->queueOccurrence->set('occurrenceId',$spOcc->get('id'));
					$lsu->queueOccurrence->set('imageId',$spOcc->get('imageId'));
					$lsu->queueOccurrence->save();
				}
			}
		}
		print json_encode( array( 'success' => true ) );
		break;

	case 'getUsers':
		include_once('./access_user/access_user_class.php');
		$accessUser = new Access_user( DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME );
		$data = $accessUser ->getUsers();
		header('Content-type: application/json');
		if($data) {
			print json_encode( array( 'success' => true ,'totalCount' => $accessUser -> getCount(), 'data' => $data));
		} else {
			print json_encode(array('success' => true, 'data' => array()));
		}
		break;

	case 'addUser':
		include_once('./access_user/access_user_class.php');
		$accessUser = new Access_user( DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME );
		$result = $accessUser ->addUser($name, $email, $permission, $password );
		header('Content-type: application/json');
		if ($result) {
			print json_encode( array( 'success' => true , 'data' => 'User added successfuly.'));
		} else {
			print json_encode( array( 'success' => false , 'error' => 'Unable to add User.'));
		}
		break;

	case 'updateUser':
		include_once('./access_user/access_user_class.php');
		$accessUser = new Access_user( DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME );
		$result = $accessUser ->updateUser($user_id, $name, $email, $permission, $password);
		header('Content-type: application/json');
		if ($result) {
			print json_encode( array( 'success' => true , 'data' => 'User updated successfuly.'));
		} else {
			print json_encode( array( 'success' => false , 'error' => 'Unable to update User.'));
		}
		break;

	case 'deleteUser':
		include_once('./access_user/access_user_class.php');
		$accessUser = new Access_user( DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME );
		$result = $accessUser ->deleteUser($user_id);
		header('Content-type: application/json');
		if ($result) {
			print json_encode( array( 'success' => true , 'data' => 'User deleted successfuly.'));
		} else {
			print json_encode( array( 'success' => false , 'error' => 'Unable to delete User.'));
		}
		break;
	
	case 'signout':
		include_once('./access_user/access_user_class.php');
		$accessUser = new Access_user( DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME );
		$result = $accessUser ->log_out();
		header('Content-type: application/json');
		if($result) {
			print json_encode( array('success' => true));
		} else {
			print json_encode( array('success' => false, 'error' => 'Unable to sign out user.'));
		}
		break;

    case 'audit':
			include('./sdk-1.3.2/sdk.class.php');
			include_once('class.speciesoccurrence.php');
			$spOcc = new SpeciesOccurrence();
			$amazon = new AmazonS3($config["s3"]["key"], $config["s3"]["sec"]);
			$statsArray = array();
			$prefix = "3x5_images/incoming/";
#			$response = $amazon->list_objects($config["s3"]["bucketname"], array('prefix' => $prefix));
			$response = $amazon->get_object_list($config["s3"]["bucketname"], array('prefix' => $prefix));
			natsort($response);

			if (is_array($response)) {
#			if($response->isOK()) {
#				$body = $response->body;
#					for($i=0;$i<count($body->Contents);$i++) {
				for($i=0;$i<count($response);$i++) {	
#					$ky = $body->Contents[$i];
#					$filePath = $ky->Key;
					$filePath = $response[$i];
					$fileDetails = @pathinfo($filePath);

					if ($fileDetails['extension'] == 'jpg' && $fileDetails['basename'][0] != ".") {
						$auth = uniqid();
						$fileName = $fileDetails['basename'];
						$spOcc->clearRecord();
						$spOcc->set('stage','Queue');
						$spOcc->set('historicalCard', 1);
						$spOcc->set('auth', $auth);
						$spOcc->set('filename',$fileName);
						$spOcc->set('originalPath', $filePath);						
						$res = $spOcc->save(1);
						if ($res != false) {	
							$insertId = $spOcc->get('id');
							$barcode = getCardName($insertId);
							$destination = getImagePath($barcode) . $barcode . '.jpg';
							//print($filePath);
							//echo "<br>";
							$temp_file = tempnam(sys_get_temp_dir(), 'Tux');
							$amazon->get_object($config["s3"]["bucketname"], $filePath, array('fileDownload' => $temp_file . $fileDetails['basename']));
							$amazon->create_object ($config["s3"]["bucketname"], $destination , array('fileUpload' => $temp_file . $fileDetails['basename'] ,'acl' => AmazonS3::ACL_PUBLIC, 'storage' => AmazonS3::STORAGE_REDUCED) );
							unlink($temp_file . $fileDetails['basename']);
				
							$imageCount++;
							$spOcc->load_by_id($insertId);
							$spOcc->set('filename',$barcode . '.jpg');
							$spOcc->set('path', $config["s3"]["basepath"] . getImagePath($barcode));
							$spOcc->set('imageId',$barcode);
							$spOcc->save(1);
					
							# populating the queue
							$lsu->queueOccurrence->set('occurrenceId',$insertId);
							$lsu->queueOccurrence->set('imageId',$barcode);
							$lsu->queueOccurrence->save();			
						}
#						if ($ik++ == 5) exit();
					} # if  jpg
				} # for contents
			} else {
					echo 'Not Ok';
			} # response ok
			header('Content-type: application/json');
			print json_encode(array( 'success' => true , 'imageCount' => $imageCount));
    break;

   /* case 'set_object':
        include('./sdk-1.3.2/sdk.class.php');
        $amazon = new AmazonS3($config["s3"]["key"],$config["s3"]["sec"]);
        $response = $amazon->create_object ( 'lsubirdcenter', 'php.jpg', array('fileUpload' => '../images/php.jpg','acl' => AmazonS3::ACL_PUBLIC, 'storage' => AmazonS3::STORAGE_REDUCED) );
       //$response = $amazon->create_object('lsubirdcenter', 'test1.txt', array( 'body' => 'This is my body text.'));
       var_dump($response->isOK());
       //$response = $amazon->get_bucket_list();
       //print_r($response);
    break;

   case 'get_object':
        include('./sdk-1.3.2/sdk.class.php');
        $amazon = new AmazonS3($config["s3"]["key"],$config["s3"]["sec"]);
        $response = $amazon->get_object('lsubirdcenter','3x5_images/incoming/2011-04-29/Image_7.jpg' );
        var_dump($response->isOK());
    break; 

    case 'test':
			include('./sdk-1.3.2/sdk.class.php');
			$amazon = new AmazonS3($config["s3"]["key"],$config["s3"]["sec"]);
			//$response = $amazon->get_bucket_list();
			$response = $amazon->list_objects($config["s3"]["bucketname"], '3x5_images/incoming/');
	    break;

    case 'auditTest':
        echo '<pre>';
        $barcode = trim($_REQUEST['barcode']);
        // $limit = $_REQUEST['limit'] = 10000;
        include('./sdk-1.3.2/sdk.class.php');
        $amazon = new AmazonS3($config["s3"]["key"],$config["s3"]["sec"]);
        $statsArray = array();

        $bucket = "lsubirdcenter";
        $prefix = "3x5_images/incoming/";
        $response = $amazon->list_objects($bucket,array('prefix' => $prefix));
        //$response = $amazon->list_objects($config["s3"]["bucketname"], '3x5_images/incoming/');
        if($response->isOK()) {
	        $body = $response->body;
            //print_r($body);

            $barcode = '';
	        $skipGtileChk = false;
	        $lastFlag = false;
           // echo '<br> Count : ' . count($body->Contents);
            for($i=0;$i<count($body->Contents);$i++){
            // if($i >= $limit) break;
	    	    $ky = $body->Contents[$i];
		        $filePath = $ky->Key;
		        $fileDetails = @pathinfo($filePath);
                //print_r($fileDetails);
                 if ($fileDetails['extension'] == 'jpg') {
                    //echo '<br> Barcode : ' . $barcode;
                    //echo '<br>';
                      print($filePath);
                      echo "<br>";
                      //print_r($fileDetails['basename']);
                      //$temp_file = tempnam(sys_get_temp_dir(), 'Tux');
                      //$amazon->get_object($bucket, $filePath, array('fileDownload' => $temp_file . $fileDetails['basename']));
                      //$amazon->create_object ($bucket, 'temp/' .$fileDetails['basename'] , array('fileUpload' => $temp_file . $fileDetails['basename'] ,'acl' => AmazonS3::ACL_PUBLIC, 'storage' => AmazonS3::STORAGE_REDUCED) );
                      //unlink($temp_file . $fileDetails['basename']);
                 }
	        } # for contents

        } else {
            echo 'Not Ok';
        } # response ok
        // $statsArray[] = array('file' => $fl['basename'], 'barcode' => $fl['filename'], 'details' => $ar);
    break;
*/

	default:
		header('Content-type: application/json');
		print json_encode(array("status" => false, "error" => "No Command Provided"));
		break;

}
?>